package com.zkingsoft.actions.app.interfaces;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.constraint.BaseController;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.distribution.DisCoupon;
import com.zkingsoft.model.distribution.DisCouponRule;
import com.zkingsoft.model.distribution.DisDesigner;
import com.zkingsoft.plugin.message.Sendsms;
import com.zkingsoft.plugin.weixin.Constants;
import com.zkingsoft.plugin.weixin.HttpRequest;
import com.zkingsoft.plugin.weixin.HttpResponse;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.distribution.DisCouponRuleService;
import com.zkingsoft.services.distribution.DisCouponService;
import com.zkingsoft.services.distribution.DisDesignerService;
import com.zkingsoft.sqlUtil.ServiceUtil;
import com.zkingsoft.util.EncrypUtil;
import com.zkingsoft.util.StringUtils;
import com.zkingsoft.util.WebUtil;

/**
 * @description 移动端页面控制器
 * @author maoluguang
 */
@Controller
@RequestMapping(value = "app")
public class AppController extends BaseController {

	@Resource
	private DisDesignerService userService;

	@Resource
	private ServiceUtil serviceUtil;
	
	@Resource
	private DisCouponService disCouponService;
	
	@Resource
	private DisCouponRuleService disCouponRuleService;

	/** 验证码 */
	private static final String YZM = "MsgCode";
	/** 手机号 */
	private static final String PHONE = "Phone";

	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "app/" + page1;
	}

	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "app/" + page1 + "/" + page2;
	}

	/**
	 * 检验邀请码
	 */
	@RequestMapping(value = "/doInviteCode")
	public @ResponseBody AjaxResult doInviteCode(String invite_code) {
		DisDesigner disDesigner = new DisDesigner();
		disDesigner.setDesInviteCode(invite_code);
		List<DisDesigner> dataList = userService.findByModel(disDesigner);
		if (dataList == null || dataList.isEmpty()) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "邀请码错误！");
		}
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, "app/toRegister?invite_code=" + invite_code, "");
		return result;
	}

	/**
	 * 前往注册页面
	 */
	@RequestMapping(value = "/toRegister")
	public String toRegister(String invite_code) {
		DisDesigner parent = new DisDesigner();
		parent.setDesInviteCode(invite_code);
		List<DisDesigner> dataList = userService.findByModel(parent);
		if (dataList == null || dataList.isEmpty()) {
			throw new GlobleException("邀请码错误！");
		}
		// 获取微信信息
		DisDesigner newDesigner = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.WEIXIN_INFO);
		if(newDesigner == null) {
			return "redirect:/app/authorize";
		}
		newDesigner.setDesParentId(dataList.get(0).getDesId());
		WebUtil.setRequestAttribute("designer", newDesigner);
		return "app/users/register";
	}

	/**
	 * 获取验证码
	 */
	@RequestMapping(value = "/getMsgCode")
	public @ResponseBody AjaxResult getMsgCode(String tel) {
		if (serviceUtil.addCheckRepeat("dis_designer", "des_account", tel)) {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机号已注册！");
		}
		try {
			String code = Sendsms.sendSms(tel);
			if(code==null || "".equals(code)){
				return new AjaxResult(AjaxResult.STATUS_ERR, null,"验证码发送失败");
			}
			WebUtil.getSession().setAttribute(YZM, code);
			// // 获取验证码
//			WebUtil.setSessionAttribute(YZM, "1234");
		} catch (Exception e) {
			throw new GlobleException("验证码发送失败！");
		}

		WebUtil.setSessionAttribute(PHONE, tel);
		return new AjaxResult(AjaxResult.STATUS_OK, "验证码发送成功！");
	}

	/**
	 * 注册
	 */
	@RequestMapping(value = "/doRegister")
	public @ResponseBody AjaxResult doRegister(DisDesigner disDesigner, String code) {
		if (WebUtil.getSession().getAttribute(YZM) == null) { // 判断验证码是否失效
			return new AjaxResult(AjaxResult.STATUS_ERR, "验证码已失效！");
		}
		if (!disDesigner.getDesAccount().equals(WebUtil.getSession().getAttribute(PHONE))) { // 判断手机是否为发送短信的手机
			return new AjaxResult(AjaxResult.STATUS_ERR, "手机号未验证！");
		}
		if (!WebUtil.getSession().getAttribute(YZM).equals(code)) { // 判断验证码是否正确
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码错误!");
		}
		if (serviceUtil.addCheckRepeat("dis_designer", "des_account", disDesigner.getDesAccount())) {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机号已注册！");
		}
		// 密码加密
		try {
			disDesigner.setDesPassword(EncrypUtil.getMD5(disDesigner.getDesPassword()));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		disDesigner.setDesInviteCode(StringUtils.getRandomString(10));
		disDesigner.setDesRebate(new BigDecimal(0));
		disDesigner.setDesRegisterTime(new Date());
		disDesigner.setDesAuditStatus("1");

		int i = userService.add(disDesigner);
		if (i > 0) {
			// 自动登录
//			WebUtil.getSession().setAttribute(SystemConstance.APP_LOGIN_KEY, disDesigner);
			AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, "app/authorize", "注册成功！");
			// result.putInMap("disDesigner", disDesigner);
			return result;
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "注册失败！");
		}
	}

	/**
	 * 前往登录页面
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/toAppLogin")
	public String toAppLogin(HttpServletRequest request) throws IOException {
		if(WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY) != null) {
			return "redirect:/app/users/toUserIndex";
		}
		// 获取微信信息
		HttpRequest wxReq = new HttpRequest();
		String code = request.getParameter("code");
		log.debug("code === " + code);
		String access_token_url = Constants.OAUTH_ACCESS_TOKEN_URL.replace("APPID", Constants.APPID)
				.replace("SECRET", Constants.APPSECRET).replace("CODE", code);
		HttpResponse wxRes = wxReq.sendHttpGet(access_token_url, null);
		JSONObject json = JSONObject.fromObject(wxRes.getDataString());
		String access_token = json.getString("access_token");
		String openid = json.getString("openid");
		log.debug("openid === " + openid);
		if (json.has("errcode")) {
			throw new GlobleException("获取openId出错! errcode ==" + json.getString("errcode"));
		}
		HttpRequest userInfoReq = new HttpRequest();
		String userInfoUrl = Constants.GET_UESER_INFO.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
		HttpResponse userInfoRes = userInfoReq.sendHttpGet(userInfoUrl, null);
		JSONObject userJson = JSONObject.fromObject(userInfoRes.getDataString());
		if (userJson.has("errcode")) {
			throw new GlobleException("获取user_info出错! errcode ===" + json.getString("errcode"));
		}
		String desOpenid = userJson.getString("openid");
		String desName = userJson.getString("nickname");
//		desName = StringUtils.strToUnicode(desName);
		String desSex = userJson.getString("sex");
		String desHeadimgurl = userJson.getString("headimgurl");

		DisDesigner wxDesigner = new DisDesigner();
		wxDesigner.setDesOpenid(desOpenid);
		wxDesigner.setDesName(desName);
		wxDesigner.setDesSex(desSex);
		wxDesigner.setDesHeadimgurl(desHeadimgurl);
		WebUtil.setSessionAttribute(SystemConstance.WEIXIN_INFO, wxDesigner);

		// ...
		String page = "";

		// 判断微信openid是否注册
		DisDesigner query = new DisDesigner();
		query.setDesOpenid(desOpenid);
		List<DisDesigner> list = userService.findByModel(query);
		if (list != null && !list.isEmpty()) {
			WebUtil.setRequestAttribute("designer", wxDesigner);
			page = "app/users/login";
		} else {
			page = "app/users/invite_code";
		}

		return page;
	}

	/**
	 * app登录
	 */
	@RequestMapping(value = "/doAppLogin")
	public @ResponseBody AjaxResult dologin(String desOpenid, String desAccount, String desPassword) {
		DisDesigner disDesigner = new DisDesigner();
		// 加密密码
		try {
			disDesigner.setDesPassword(EncrypUtil.getMD5(desPassword));
		} catch (UnsupportedEncodingException e) {
			throw new GlobleException("登录失败！");
		}
		disDesigner.setDesOpenid(desOpenid);
		disDesigner.setDesAccount(desAccount);
		List<DisDesigner> list = userService.findByModel(disDesigner);
		if (list == null || list.isEmpty()) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "帐号或密码错误！");
		}
		disDesigner = list.get(0);
		if (!"2".equals(disDesigner.getDesAuditStatus())) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "帐号待审核！");
		}
		WebUtil.setSessionAttribute(SystemConstance.APP_LOGIN_KEY, disDesigner);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, "app/users/toUserIndex", "登录成功！");
		// result.putInMap("disDesigner", disDesigner);
		return result;
	}

	Logger log = Logger.getLogger(AppController.class);

	@RequestMapping(value = "/authorize")
	public String index(HttpServletRequest request) throws Exception {
		String timestamp = "" + System.currentTimeMillis();
		String url = Constants.OAUTH_AUTHORIZE_URL.replace("APPID", Constants.APPID)
				.replace("REDIRECT_URI", "http%3A%2F%2Fashley.zkingsoft.com%2Fapp%2FtoAppLogin")
				.replace("SCOPE", "snsapi_userinfo").replace("STATE", timestamp);
		return "redirect:" + url;
	}
	
	/**
	 * 前往分享优惠券页面
	 */
	@RequestMapping(value = "/toCouponDetail")
	public String toCouponDetail(Long id) {
		boolean isShare;
		DisDesigner appLoginUser = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		if(appLoginUser != null) {
			isShare = true;
		} else {
			isShare = false;
		}
		
		// 获取微信信息
		try {
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			String noncestr = UUID.randomUUID().toString().replace("-", "");
			String ticket = getJsapiTicket();
			String shareUrl = getCurrentUrl();
			String signature = getSignature(timestamp, noncestr, ticket,
					shareUrl);
			WebUtil.getRequest().setAttribute("appId", Constants.APPID);
			WebUtil.getRequest().setAttribute("timestamp", timestamp);
			WebUtil.getRequest().setAttribute("noncestr", noncestr);
			WebUtil.getRequest().setAttribute("signature", signature);
			WebUtil.getRequest().setAttribute("shareUrl", shareUrl);
			WebUtil.getRequest().setAttribute("jsapi_ticket", ticket);
		} catch (Exception e) {
			e.printStackTrace();
			throw new GlobleException(e.getMessage());
		}
		DisCoupon coupon = disCouponService.findById(id);
		if(coupon != null) {
			DisCouponRule disCouponRule = disCouponRuleService.findById(coupon.getCouponRuleId());
			coupon.setDisCouponRule(disCouponRule);
		}
		WebUtil.setRequestAttribute("coupon", coupon);
		WebUtil.setRequestAttribute("isShare", isShare);
		
		return "app/users/user_coupon_detail";
	}

	/**
	 * @throws IOException
	 *             生成签名的随机串 @Title: getNoncestr @Description: TODO @param @return
	 *             设定文件 @return String 返回类型 @throws
	 */
	private String getJsapiTicket() throws IOException {
		String url1 = Constants.GET_ACCESS_TOKEN_WITHOUTAUTH.replace("APPID",
				Constants.APPID).replace("APPSECRET", Constants.APPSECRET);
		HttpRequest reqObj = new HttpRequest();
		HttpResponse result = reqObj.sendHttpGet(url1, null);
		JSONObject ujson = JSONObject.fromObject(result.getDataString());
		String accesstoken = ujson.getString("access_token");

		String url2 = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
				+ accesstoken + "&type=jsapi";
		HttpRequest reqObj2 = new HttpRequest();
		HttpResponse result2 = reqObj2.sendHttpGet(url2, null);
		JSONObject ujson2 = JSONObject.fromObject(result2.getDataString());
		String ticket = ujson2.getString("ticket");
		return ticket;
	}
	
	private String getCurrentUrl() {

		HttpServletRequest httpRequest = (HttpServletRequest) WebUtil.getRequest();
		String strBackUrl = "http://" + WebUtil.getRequest().getServerName() // 服务器地址
				 //	+ ":" + WebUtil.getRequest().getServerPort()
				+ httpRequest.getContextPath() // 项目名称
				+ httpRequest.getServletPath() // 请求页面或其他地址
				+ "?" + (httpRequest.getQueryString()); // 参数
		return strBackUrl;
	}

	private String getSignature(String timestamp, String noncestr,
			String jsapiTicket, String share2FirendUrl)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		String signature = "jsapi_ticket=" + jsapiTicket + "&noncestr="
				+ noncestr + "&timestamp=" + timestamp + "&url="
				+ share2FirendUrl;
		MessageDigest crypt = MessageDigest.getInstance("SHA-1");
		crypt.reset();
		System.out.println(" sha1Hex  signature before= " + signature);
		crypt.update(signature.getBytes("UTF-8"));
		signature = byteToHex(crypt.digest());
		System.out.println(" sha1Hex  signature = " + signature);
		return signature;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}
	
	@RequestMapping(value="/toBinding")
	public String toBinding() {
		// 获取微信信息
		DisDesigner newDesigner = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.WEIXIN_INFO);
		if(newDesigner == null) {
			return "redirect:/app/authorize";
		}
		WebUtil.setRequestAttribute("designer", newDesigner);
		return "app/users/binding";
	}

	@RequestMapping(value="/doBinding")
	@ResponseBody
	public AjaxResult doBinding(DisDesigner disDesigner) {
		
		DisDesigner query = new DisDesigner();
		// 加密密码
		try {
			query.setDesPassword(EncrypUtil.getMD5(disDesigner.getDesPassword()));
		} catch (UnsupportedEncodingException e) {
			throw new GlobleException("绑定失败！");
		}
		query.setDesAccount(disDesigner.getDesAccount());
		List<DisDesigner> list = userService.findByModel(query);
		if (list == null || list.isEmpty()) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "帐号或密码错误！");
		}
		query = list.get(0);
		if(StringUtils.isNotBlank(query.getDesOpenid()) && !query.getDesOpenid().equals(disDesigner.getDesOpenid())) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "帐号已被绑定！");
		}
		if (!"2".equals(query.getDesAuditStatus())) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "帐号待审核！");
		}
		query.setDesOpenid(disDesigner.getDesOpenid());
		query.setDesName(disDesigner.getDesName());
		query.setDesSex(disDesigner.getDesSex());
		query.setDesHeadimgurl(disDesigner.getDesHeadimgurl());
		
		int i = userService.modifyByModel(query);
		if (i > 0) {
			WebUtil.setSessionAttribute(SystemConstance.APP_LOGIN_KEY, query);
			AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, "app/users/toUserIndex", "绑定成功！");
			// result.putInMap("disDesigner", disDesigner);
			return result;
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, "绑定失败！");
		}
	}
	
	
	/**
	 * 前往寻找门店页面
	 */
	@RequestMapping(value = "/toSearchStore")
	public String toSearchStore() {
		// 获取微信信息
		try {
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			String noncestr = UUID.randomUUID().toString().replace("-", "");
			String ticket = getJsapiTicket();
			String shareUrl = "http://" + WebUtil.getRequest().getServerName() // 服务器地址
					+ WebUtil.getRequest().getContextPath() // 项目名称
					+ WebUtil.getRequest().getServletPath(); // 请求页面或其他地址;
			String signature = getSignature(timestamp, noncestr, ticket, shareUrl);
			WebUtil.getRequest().setAttribute("appId", Constants.APPID);
			WebUtil.getRequest().setAttribute("timestamp", timestamp);
			WebUtil.getRequest().setAttribute("noncestr", noncestr);
			WebUtil.getRequest().setAttribute("signature", signature);
			WebUtil.getRequest().setAttribute("jsapi_ticket", ticket);
		} catch (Exception e) {
			e.printStackTrace();
			throw new GlobleException(e.getMessage());
		}
		return "app/users/search_store";
	}
	
}
